<script setup lang="ts">
import { uploadImage } from '@/services/consult'
import { useConsultStore } from '@/stores'
import type { ConsultIllness, Image } from '@/types/consult'
import { Dialog, Toast } from 'vant'
import type {
  UploaderAfterRead,
  UploaderFileListItem
} from 'vant/lib/uploader/types'
import { computed, onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { timeOptions, flagOptions } from '@/services/constants'

const store = useConsultStore()
const router = useRouter()

// 1. 收集病情描述信息对象
const form = ref<ConsultIllness>({
  illnessDesc: '',
  illnessTime: undefined,
  consultFlag: undefined,
  pictures: []
})

// 2. 界面搭建的选项数据

// 3. 图片上传
// 3.1 文件关联数组
const list = ref<Image[]>([])
// 3.2 文件读取完毕后调用
const onAfterRead: UploaderAfterRead = async (item) => {
  // 上传前校验
  if (Array.isArray(item)) return Toast('只支持单文件上传~')
  if (!item.file) return Toast('上传的文件有点问题~')

  item.status = 'uploading'
  item.message = '上传中...'
  // 调用接口
  try {
    const res = await uploadImage(item.file)
    item.status = 'done'
    item.message = '上传成功'
    item.url = res.data.url
    form.value.pictures?.push(res.data)
  } catch (error) {
    item.status = 'failed'
    item.message = '上传失败...'
  }
}
// 3.3 删除单个文件
const onDelete = (item: UploaderFileListItem) => {
  // console.log(item)
  form.value.pictures = form.value.pictures?.filter(
    (pic) => pic.url !== item.url
  )
}

// 4. 下一步
// 4.1 控制按钮样式
const disabled = computed(
  () =>
    !form.value.illnessDesc ||
    form.value.illnessTime === undefined ||
    form.value.consultFlag === undefined
)

// 4.2 点击下一步按钮
const next = () => {
  // 4.2.1 校验
  if (!form.value.illnessDesc) return Toast('请输入病情描述~')
  if (form.value.illnessTime === undefined) return Toast('请选择患病时间~')
  if (form.value.consultFlag === undefined) return Toast('请选择是否就诊过~')
  // 4.2.2 存储数据
  store.setIllness(form.value)
  // 4.2.3 跳转到下一个页面
  router.push('/user/patient?isChange=1')
}

// 5. 回显数据
// 后面界面回来, 刷新页面, 前面页面进来 --> 本地存储有病情信息即可
onMounted(() => {
  // 5.1 判断本地是否存储有数据
  if (store.consult.illnessDesc) {
    Dialog.confirm({
      title: '温馨提示',
      message: '是否恢复您之前填写的病历信息呢?',
      confirmButtonColor: 'var(--cp-primary)',
      closeOnPopstate: false
    }).then(() => {
      const { illnessDesc, illnessTime, consultFlag, pictures } = store.consult
      form.value = { illnessDesc, illnessTime, consultFlag, pictures }
      // 给组件双向绑定的list数组赋值
      list.value = pictures || []
    })
  }
})
</script>

<template>
  <div class="consult-illness-page">
    <!-- 导航条 -->
    <cp-nav-bar title="图文问诊" />
    <!-- 头部 - 医生提示-->
    <div class="illness-tip van-hairline--bottom">
      <img class="img" src="@/assets/avatar-doctor.svg" />
      <div class="info">
        <p class="tit">在线医生</p>
        <p class="tip">
          请描述你的疾病或症状、是否用药、就诊经历，需要我听过什么样的帮助
        </p>
        <p class="safe">
          <cp-icon name="consult-safe" /><span>内容仅医生可见</span>
        </p>
      </div>
    </div>
    <div class="illness-form">
      <van-field
        type="textarea"
        rows="3"
        placeholder="请详细描述您的病情，病情描述不能为空"
        v-model="form.illnessDesc"
      ></van-field>
      <div class="item">
        <p>本次患病多久了？</p>
        <cp-radio-btn :options="timeOptions" v-model="form.illnessTime" />
      </div>
      <div class="item">
        <p>此次病情是否去医院就诊过？</p>
        <cp-radio-btn :options="flagOptions" v-model="form.consultFlag" />
      </div>
      <div class="illness-img">
        <van-uploader
          v-model="list"
          upload-text="上传图片"
          upload-icon="photo-o"
          :max-count="9"
          :max-size="5 * 1024 * 1024"
          :after-read="onAfterRead"
          @delete="onDelete"
        ></van-uploader>
        <p class="tip" v-if="list.length === 0">
          上传内容仅医生可见,最多9张图,最大5MB
        </p>
      </div>
    </div>
    <!-- 下一步 -->
    <van-button :class="{ disabled }" @click="next" type="primary" block round
      >下一步</van-button
    >
  </div>
</template>

<style lang="scss" scoped>
.consult-illness-page {
  padding-top: 46px;
  .illness-tip {
    display: flex;
    padding: 15px;
    .img {
      width: 52px;
      height: 52px;
      border-radius: 4px;
      overflow: hidden;
      margin-top: 10px;
    }
    .info {
      flex: 1;
      padding-left: 12px;
      .tit {
        font-size: 16px;
        margin-bottom: 5px;
      }
      .tip {
        padding: 12px;
        background: var(--cp-bg);
        color: var(--cp-text3);
        font-size: 13px;
        margin-bottom: 10px;
      }
      .safe {
        font-size: 10px;
        color: var(--cp-text3);
        display: flex;
        align-items: center;
        .cp-icon {
          font-size: 12px;
          margin-right: 2px;
        }
      }
    }
  }

  .illness-form {
    padding: 15px;
    .van-field {
      padding: 0;
      &::after {
        border-bottom: none;
      }
    }
    .item {
      > p {
        color: var(--cp-text3);
        padding: 15px 0;
      }
    }
  }

  .illness-img {
    padding-top: 16px;
    margin-bottom: 40px;
    display: flex;
    align-items: center;
    .tip {
      font-size: 12px;
      color: var(--cp-tip);
    }
    ::v-deep() {
      .van-uploader {
        &__preview {
          &-delete {
            left: -6px;
            top: -6px;
            border-radius: 50%;
            background-color: var(--cp-primary);
            width: 20px;
            height: 20px;
            &-icon {
              transform: scale(0.9) translate(-22%, 22%);
            }
          }
          &-image {
            border-radius: 8px;
            overflow: hidden;
          }
        }
        &__upload {
          border-radius: 8px;
        }
        &__upload-icon {
          color: var(--cp-text3);
        }
      }
    }
  }
}

.van-button {
  font-size: 16px;
  margin-bottom: 30px;
  &.disabled {
    opacity: 1;
    background: #fafafa;
    color: #d9dbde;
    border: #fafafa;
  }
}
</style>
